<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>【JDK源码笔记】- 不能再被问住了！ReentrantLock 源码、画图一起看一看！ | 程序员小航</title><meta name="keywords" content="源码笔记,JDK"><meta name="author" content="liuzhihang"><meta name="copyright" content="liuzhihang"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="在阅读完 JUC 包下的 AQS 源码之后，其中有很多疑问，最大的疑问就是 state 究竟是什么含义？并且 AQS 主要定义了队列的出入，但是获取资源、释放资源都是交给子类实现的，那子类是怎么实现的呢？">
<meta property="og:type" content="article">
<meta property="og:title" content="【JDK源码笔记】- 不能再被问住了！ReentrantLock 源码、画图一起看一看！">
<meta property="og:url" content="https://liuzhihang.com/2020/07/25/source-code-reentrant-lock.html">
<meta property="og:site_name" content="程序员小航">
<meta property="og:description" content="在阅读完 JUC 包下的 AQS 源码之后，其中有很多疑问，最大的疑问就是 state 究竟是什么含义？并且 AQS 主要定义了队列的出入，但是获取资源、释放资源都是交给子类实现的，那子类是怎么实现的呢？">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantLock-RljCvj.jpeg">
<meta property="article:published_time" content="2020-07-25T01:50:00.000Z">
<meta property="article:modified_time" content="2020-12-27T09:23:14.595Z">
<meta property="article:author" content="liuzhihang">
<meta property="article:tag" content="源码笔记">
<meta property="article:tag" content="JDK">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantLock-RljCvj.jpeg"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/favicon.ico"><link rel="canonical" href="https://liuzhihang.com/2020/07/25/source-code-reentrant-lock"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//pingjs.qq.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google_site_verification" content="GZshAnnrC-4eCrl5h-e_5Rdk4lOUhRK7ShULoRi2q0E"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-126394362-1"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-126394362-1');
</script><script>var _mtac = {};
(function() {
    var mta = document.createElement("script");
    mta.src = "//pingjs.qq.com/h5/stats.js?v2.0.4";
    mta.setAttribute("name", "MTAH5");
    mta.setAttribute("sid", "66540676");
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(mta, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":730,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: undefined,
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '【JDK源码笔记】- 不能再被问住了！ReentrantLock 源码、画图一起看一看！',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2020-12-27 17:23:14'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="//at.alicdn.com/t/font_1608878_xsf93f0c1a.css"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="程序员小航" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantLock-RljCvj.jpeg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">程序员小航</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">【JDK源码笔记】- 不能再被问住了！ReentrantLock 源码、画图一起看一看！</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-07-25T01:50:00.000Z" title="发表于 2020-07-25 09:50:00">2020-07-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2020-12-27T09:23:14.595Z" title="更新于 2020-12-27 17:23:14">2020-12-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/JDK/">JDK</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>9分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="【JDK源码笔记】- 不能再被问住了！ReentrantLock 源码、画图一起看一看！"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2020/07/25/source-code-reentrant-lock.html#post-comment"><span class="gitalk-comment-count"></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p>在阅读完 JUC 包下的 AQS 源码之后，其中有很多疑问，最大的疑问就是 state 究竟是什么含义？并且 AQS 主要定义了队列的出入，但是获取资源、释放资源都是交给子类实现的，那子类是怎么实现的呢？下面开始了解 ReentrantLock。 </p>
</blockquote>
<h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><p>一个可重入的互斥锁与隐式监视器锁synchronized具有相同的基本行为和语义，但功能更强大。</p>
<p>具有以下特征：</p>
<ol>
<li>互斥性：同时只有一个线程可以获取到该锁，此时其他线程请求获取锁，会被阻塞，然后被放到该锁内部维护的一个 AQS 阻塞队列中。</li>
<li>可重入性：维护 state 变量，初始为 0，当一个线程获取到锁时，state 使用 cas 更新为 1，本线程再次申请获取锁，会对 state 进行 CAS 递增，重复获取次数即 state，最多为 2147483647 。试图超出此限制会从锁定方法抛出 Error。</li>
<li>公平/非公平性：在初始化时，可以通过构造器传参，指定是否为公平锁，还是非公平锁。当设置为 true 时，为公平锁，线程争用锁时，会倾向于等待时间最长的线程。</li>
</ol>
<h4 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h4><pre><code class="java">class X &#123;
    private final ReentrantLock lock = new ReentrantLock();
    // ...

    public void m() &#123;
        lock.lock();  // block until condition holds
        try &#123;
        // ... method body
        &#125; finally &#123;
        lock.unlock()
        &#125;
&#125;
&#125;</code></pre>
<h4 id="问题疑问？"><a href="#问题疑问？" class="headerlink" title="问题疑问？"></a>问题疑问？</h4><p>首先在阅读本文时，对 AQS 有了一定的了解，如果不了解的话，可以看以下之前的文章。<a href="">图文讲解 AQS</a></p>
<ol>
<li>在 AQS 中介绍 state 时，说 state 含义由子类进行定义，那在 ReentrantLock 中 state 代表什么？</li>
<li>ReentrantLock 和 AQS 有什么关系？</li>
<li>线程是如何获取到锁的？</li>
<li>锁的可重入性是如何实现的？</li>
<li>当前线程获取锁失败，被阻塞的后续操作是什么？</li>
<li>公平锁和非公平锁是如何体现的？</li>
<li>锁是如何释放的？</li>
</ol>
<p>将通过源码及画图的方式，围绕上面几个问题，展开阅读和分析。</p>
<h3 id="源码分析"><a href="#源码分析" class="headerlink" title="源码分析"></a>源码分析</h3><h4 id="基本结构"><a href="#基本结构" class="headerlink" title="基本结构"></a>基本结构</h4><p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantLock-uml-DDnlDW.png" alt="ReentrantLock-uml-DDnlDW"></p>
<p>基本结构如图所示，ReentrantLock 类实现了接口 Lock，在接口 Lock 中定义了使用锁时的方法，方法及含义如下：</p>
<pre><code class="java">public interface Lock &#123;

    // 获取锁，如果没有获取到，会阻塞。
    void lock();

    // 获取锁，如果没有获取到，会阻塞。响应中断。
    void lockInterruptibly() throws InterruptedException;

    // 尝试获取锁，如果获取到，返回 true，没有获取到 返回 false
    boolean tryLock();

    // 尝试获取锁，没有有获取到，会等待指定时间，响应中断。
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;

    // 释放锁
    void unlock();
&#125;</code></pre>
<p>而 ReentrantLock 也只是实现了 Lock 接口，并实现了这些方法，那 ReentrantLock 和 AQS 到底有什么关系呢？这就需要看内部具体如何实现的了。</p>
<p>通过上面类图可以看出，在 ReentrantLock 中含有两个内部类，分别是 NonfairSync FairSync 而它俩又实现了 抽象类 Sync，抽象类 Sync 继承了 AbstractQueuedSynchronizer 即 AQS。具体代码如下：</p>
<pre><code class="java">public class ReentrantLock implements Lock, java.io.Serializable &#123;

    private final Sync sync;

    // 锁的同步控制基础类。 子类具体到公平和非公平的版本。 使用AQS状态来表示持有该锁的数量。
    abstract static class Sync extends AbstractQueuedSynchronizer &#123; 
        // 省略 ...
    &#125;

    static final class NonfairSync extends Sync &#123; 
        // 非公平锁逻辑 省略 ...
    &#125;

    static final class FairSync extends Sync &#123; 
        // 公平锁逻辑 省略 ...
    &#125;
    // 默认非公平锁
    public ReentrantLock() &#123;
        sync = new NonfairSync();
    &#125;
    // 根据传参指定公平锁还是非公平锁，true 公平锁，false 非公平锁
    public ReentrantLock(boolean fair) &#123;
        sync = fair ? new FairSync() : new NonfairSync();
    &#125;
&#125;
</code></pre>
<p>通过上面代码可以看出：</p>
<ol>
<li>锁的基本控制是由 NonfairSync 和 FairSync 进行控制的，而它俩的父类 Sync 继承了 AQS (AbstractQueuedSynchronizer)，这也就是说明 ReentrantLock 的实现和 AQS 是有关的。</li>
<li>NonfairSync 代表非公平锁实现逻辑，FairSync 代表公平锁实现逻辑。</li>
<li>构造器传参可以看出，初始化时，默认为 NonfairSync 非公平锁。也可以指定声明为公平锁或非公平锁，传参 true 为 公平锁，false 为非公平锁。</li>
</ol>
<p>具体 ReentrantLock 和 AQS 的关系是怎样的，就需要通过加锁的过程来分析了。</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/878c841a671f102ddc2cdeae35faa4cc-pKLxAS.gif" alt="878c841a671f102ddc2cdeae35faa4cc-pKLxAS"></p>
<h4 id="lock"><a href="#lock" class="headerlink" title="lock"></a>lock</h4><p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantLock-lock-4apftk.png" alt="ReentrantLock-lock-4apftk"></p>
<p>如图所示，默认声明非公平锁，lock 方法内部调用 <code>sync.lock();</code> 此时应该是使用的非公平锁内部的 lock 加锁操作。</p>
<pre><code class="java">final void lock() &#123;
    // 通过 CAS 设置 state 值 0 -&gt; 1
    if (compareAndSetState(0, 1))
        // 设置成功当前线程获取到了锁
        setExclusiveOwnerThread(Thread.currentThread());
    else
        // 设置失败，则调用 AQS 的方法，尝试获取锁。
        acquire(1);
&#125;</code></pre>
<ol>
<li>首先会 使用 CAS 更新 state 的值， 此时就会发现， state 在这里代表的锁的状态。 0 未加锁，1 加锁。</li>
<li>设置失败，会调用 AQS 的 acquire(1); 方法。</li>
</ol>
<p>再看下 AQS 的 acquire 代码</p>
<pre><code class="java">public final void acquire(int arg) &#123;
    // tryAcquire 尝试获取 state，获取失败则会加入到队列
    if (!tryAcquire(arg) &amp;&amp; acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
&#125;</code></pre>
<p>在之前分析 AQS 源码时，已经介绍 tryAcquire 是尝试获取 state 的值，AQS 中并不提供可用的方法，此处是由子类实现的。所以这块代码还是在 NonfairSync 类中自己实现的业务逻辑。</p>
<pre><code class="java">static final class NonfairSync extends Sync &#123;
    // NonfairSync 实现
    protected final boolean tryAcquire(int acquires) &#123;
        // 调用父类的方法
        return nonfairTryAcquire(acquires);
    &#125;
&#125;
abstract static class Sync extends AbstractQueuedSynchronizer &#123;
    // NonfairSync 的父类 Sync 中有实现
    // state 传参是 1
    final boolean nonfairTryAcquire(int acquires) &#123;
        // 获取当前线程
        final Thread current = Thread.currentThread();
        // 获取 state
        int c = getState();
        // 如果 c 是 0 
        if (c == 0) &#123;
            // 使用 cas 更新为 1
            if (compareAndSetState(0, acquires)) &#123;
                // 设置持有线程为当前
                setExclusiveOwnerThread(current);
                return true;
            &#125;
        &#125; else if (current == getExclusiveOwnerThread()) &#123;
            // 如果是当前线程持有
            // 对 state 进行累加
            int nextc = c + acquires;
            // 不允许超过 int 的最大值 2147483647 + 1 = -2147483648
            if (nextc &lt; 0) // overflow
                throw new Error(&quot;Maximum lock count exceeded&quot;);
            // 设置 state 的值
            setState(nextc);
            return true;
        &#125;
        return false;
    &#125;
&#125;</code></pre>
<ol>
<li>当前线程加锁，直接使用 CAS 方式对 state 从 0 更新为 1，更新成功，则获得锁，更新失败，则获取失败。</li>
<li>更新失败后会调用 AQS 的 <code>acquire(1);</code> 方法， 此处传参为 1。</li>
<li>tryAcquire 再次尝试获取锁。<ol>
<li>state 是 0，尝试获取。获取成功返回 true；</li>
<li>state 不是 0，判断是否为当前线程持有，是当前线程持有则对 state 进行累加。</li>
</ol>
</li>
<li>tryAcquire 获取锁失败，则走 AQS 的 acquireQueued 逻辑，创建节点，并加入到等待队列中。</li>
</ol>
<p>流程画图如下：</p>
<ul>
<li>初始为单个线程</li>
</ul>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantLock-1-1ozuSU.png" alt="ReentrantLock-1-1ozuSU"></p>
<ul>
<li>此时其他线程来请求获取锁</li>
</ul>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantLock-2-zO9REa.png" alt="ReentrantLock-2-zO9REa"></p>
<ul>
<li>加锁流程图</li>
</ul>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantLock-nonfair-LcRGc7.png" alt="ReentrantLock-nonfair-LcRGc7"></p>
<h4 id="再来看下公平锁是如何体现的？"><a href="#再来看下公平锁是如何体现的？" class="headerlink" title="再来看下公平锁是如何体现的？"></a>再来看下公平锁是如何体现的？</h4><pre><code class="java">static final class FairSync extends Sync &#123;
    private static final long serialVersionUID = -3000897897090466540L;

    final void lock() &#123;
        acquire(1);
    &#125;

    protected final boolean tryAcquire(int acquires) &#123;
        final Thread current = Thread.currentThread();
        int c = getState();
        if (c == 0) &#123;
            // 判断有无节点排队
            if (!hasQueuedPredecessors() &amp;&amp;
                compareAndSetState(0, acquires)) &#123;
                setExclusiveOwnerThread(current);
                return true;
            &#125;
        &#125;
        else if (current == getExclusiveOwnerThread()) &#123;
            int nextc = c + acquires;
            if (nextc &lt; 0)
                throw new Error(&quot;Maximum lock count exceeded&quot;);
            setState(nextc);
            return true;
        &#125;
        return false;
    &#125;
&#125;</code></pre>
<p>拉出来代码比较一下：</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/compare-UFOHD0.png" alt="compare-UFOHD0"></p>
<p>可以看出在公平锁（FairSync）中多了一个判断条件</p>
<p><strong><code>!hasQueuedPredecessors()</code></strong></p>
<p>hasQueuedPredecessors 方法在 AQS 中，如果有当前线程前面的线程排队返回true，如果当前线程是在队列的头部或队列为空，返回false。</p>
<p>代码如下：</p>
<pre><code class="java">public final boolean hasQueuedPredecessors() &#123;

    Node t = tail; 
    Node h = head;
    Node s;

    return h != t &amp;&amp; ((s = h.next) == null || s.thread != Thread.currentThread());
&#125;</code></pre>
<p>如果当前加锁时已经有节点在排队，那就去节点尾部排队，否则才会去抢占锁。</p>
<p>到这里基本上已经知道公平锁和非公平锁的区别了：</p>
<p>非公平锁：不管有没有节点在排队，都会试图去获取锁，如果获取失败，进入 acquire 方法，还是会试图获取一次，之后才会进入队列中。<br>公平锁：已经有节点在排队，那就自己去节点后面排队。</p>
<h4 id="tryLock"><a href="#tryLock" class="headerlink" title="tryLock"></a>tryLock</h4><pre><code class="java">
public boolean tryLock() &#123;
    return sync.nonfairTryAcquire(1);
&#125;</code></pre>
<p>直接调用的 Sync 中的 nonfairTryAcquire， 尝试获取锁，获取失败，就返回 false，获取到锁或者是当前线程持有锁则对 state 累加后都返回 true。</p>
<h4 id="unlock"><a href="#unlock" class="headerlink" title="unlock"></a>unlock</h4><pre><code class="java">public void unlock() &#123;
    sync.release(1);
&#125;</code></pre>
<p>发现 unlock 直接调用的 AQS 的 release 方法，进行释放资源。</p>
<pre><code class="java">public final boolean release(int arg) &#123;
    if (tryRelease(arg)) &#123;
        Node h = head;
        if (h != null &amp;&amp; h.waitStatus != 0)
            unparkSuccessor(h);
        return true;
    &#125;
    return false;
&#125;</code></pre>
<p>这块在 AQS 中有介绍，也说明 tryRelease 由子类进行实现，现在在 ReentrantLock 重点关注 tryRelease 的实现。</p>
<pre><code class="java">// 释放资源，传入值为 1
protected final boolean tryRelease(int releases) &#123;
    int c = getState() - releases;
    if (Thread.currentThread() != getExclusiveOwnerThread())
        throw new IllegalMonitorStateException();
    boolean free = false;
    if (c == 0) &#123;
        free = true;
        setExclusiveOwnerThread(null);
    &#125;
    setState(c);
    return free;
&#125;</code></pre>
<ol>
<li>获取当前的 state 进行 -1 操作；</li>
<li>判断了下当前线程是否为持有线程；</li>
<li>如果释放完之后 state 为 0 ，则设置持有线程为 null；</li>
<li>更新并返回 state 的值。</li>
</ol>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>通过上面的源码及画图，基本上对开始的问题已经有了答案：</p>
<p><strong>Q</strong>：在 AQS 中介绍 state 时，说 state 含义由子类进行定义，那在 ReentrantLock 中 state 代表什么？<br><strong>A</strong>：在 ReentrantLock 中 state 代表加锁状态，0 没有线程获得锁，大于等于 1 已经有线程获得锁，大于 1 说明该获得锁的线程多次重入。</p>
<p><strong>Q</strong>：ReentrantLock 和 AQS 有什么关系？<br><strong>A</strong>：ReentrantLock 内部基于 AQS 实现，无论是锁状态，还是进入等待队列，锁释放等都是基于 AQS 实现。ReentrantLock 的公平锁和非公平锁都是 NonfairSync、FairSync 来实现的，而他们的父类 Sync 继承了 AQS。</p>
<p><strong>Q</strong>：线程是如何获取到锁的？<br><strong>A</strong>：线程通过修改 state 字段的状态来获取到锁。</p>
<p><strong>Q</strong>：锁的可重入性是如何实现的？<br><strong>A</strong>：当前线程发现 state 不是 0 ，则说明有锁已经被获取了，此时会判断当前获取到锁的线程是不是自己，如果是，则对 state 进行累加。</p>
<p><strong>Q</strong>：当前线程获取锁失败，被阻塞的后续操作是什么？<br><strong>A</strong>：获取失败，会放到 AQS 等待队列中，在队列中不断循环，监视前一个节点是否为 head ，是的话，会重新尝试获取锁。</p>
<p><strong>Q</strong>：公平锁和非公平锁是如何体现的？<br><strong>A</strong>：公平锁主要体现在如果当前队列中已经有排队的线程了，则自己直接排在后面。非公平锁是不管当前队列都没有线程排队，都会直接尝试修改 state 获取锁。</p>
<p><strong>Q</strong>：锁是如何释放的？<br><strong>A</strong>：锁释放资源，即将 state 进行 -1 操作，如果 -1 后 state 为 0，则释放节点，后续节点尝试获取锁。此处可以看 AQS 相关逻辑。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">liuzhihang</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://liuzhihang.com/2020/07/25/source-code-reentrant-lock.html">https://liuzhihang.com/2020/07/25/source-code-reentrant-lock.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://liuzhihang.com" target="_blank">程序员小航</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a><a class="post-meta__tags" href="/tags/JDK/">JDK</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantLock-RljCvj.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/07/27/source-code-reentrant-read-write-lock.html"><img class="prev-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantReadWriteLock-1ZuPsX.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">【JDK源码笔记】- 快进来！花几分钟看一下 ReentrantReadWriteLock 的原理！</div></div></a></div><div class="next-post pull-right"><a href="/2020/07/18/work-archetype.html"><img class="next-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/archetype-qNA1BU.jpeg" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">【工作笔记】- 老大说新项目的结构和 xxx 项目一样就可以了，我 ……</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2020/07/12/source-code-aqs.html" title="【JDK源码笔记】- 别走！这里有个笔记：图文讲解 AQS ，一起看看 AQS 的源码……(图文较长)"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/aqs-uhgQnu.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-07-12</div><div class="title">【JDK源码笔记】- 别走！这里有个笔记：图文讲解 AQS ，一起看看 AQS 的源码……(图文较长)</div></div></a></div><div><a href="/2020/09/27/source-code-arrayblockingqueue.html" title="【JDK源码笔记】- 基于数组的有界阻塞队列 —— ArrayBlockingQueue"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ArrayBlockingQueue-cover-ESuNmo.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-09-27</div><div class="title">【JDK源码笔记】- 基于数组的有界阻塞队列 —— ArrayBlockingQueue</div></div></a></div><div><a href="/2020/06/12/source-code-cas.html" title="【JDK源码笔记】- 从JUC源码看CAS，我做了个笔记 ......"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/cas.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-06-12</div><div class="title">【JDK源码笔记】- 从JUC源码看CAS，我做了个笔记 ......</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="gitalk-container"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">liuzhihang</div><div class="author-info__description">学，然后知不足；教，然后知困。</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liuzhihang"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liuzhihang" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&amp;email=Vjo-Iyw_Pz43ODElFicneDU5Ow" target="_blank" title="Email"><i class="fas fa-envelope-open"></i></a><a class="social-icon" href="https://weibo.com/onlyhang" target="_blank" title="Weibo"><i class="fab fa-weibo"></i></a><a class="social-icon" href="https://twitter.com/liuzhihangs" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="fas fa-rss"></i></a><a class="social-icon" href="https://www.infoq.cn/u/liuzhihang/publish" target="_blank" title="InfoQ"><i class="iconfont iconweibiaoti-1"></i></a><a class="social-icon" href="https://juejin.im/user/1987506650493117" target="_blank" title="掘金"><i class="iconfont iconjuejin-1"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_36535538" target="_blank" title="CSDN"><i class="iconfont iconcsdn"></i></a><a class="social-icon" href="https://www.zhihu.com/people/liuzhihang" target="_blank" title="知乎"><i class="iconfont iconzhihu1"></i></a><a class="social-icon" href="https://leetcode-cn.com/u/liuzhihang" target="_blank" title="LeetCode"><i class="iconfont iconleetcode"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">🧑‍💻感谢访问本站，若喜欢请收藏 ^_^ <br> <br> <img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/wechat.jpg"> <br> 个人公众号:『 程序员小航 』</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%8B%E7%BB%8D"><span class="toc-text">介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="toc-text">基本使用</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%97%AE%E9%A2%98%E7%96%91%E9%97%AE%EF%BC%9F"><span class="toc-text">问题疑问？</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90"><span class="toc-text">源码分析</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E7%BB%93%E6%9E%84"><span class="toc-text">基本结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#lock"><span class="toc-text">lock</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%86%8D%E6%9D%A5%E7%9C%8B%E4%B8%8B%E5%85%AC%E5%B9%B3%E9%94%81%E6%98%AF%E5%A6%82%E4%BD%95%E4%BD%93%E7%8E%B0%E7%9A%84%EF%BC%9F"><span class="toc-text">再来看下公平锁是如何体现的？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#tryLock"><span class="toc-text">tryLock</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#unlock"><span class="toc-text">unlock</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-text">总结</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/uztio4-T5n5Wm.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="使用 SpringBoot 转换器将前端参数转换为枚举"/></a><div class="content"><a class="title" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举">使用 SpringBoot 转换器将前端参数转换为枚举</a><time datetime="2021-09-03T23:00:00.000Z" title="发表于 2021-09-04 07:00:00">2021-09-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ze1d2z-wXDWp0.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="MyBatis-Plus 中 Mapper 重载踩坑指南"/></a><div class="content"><a class="title" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南">MyBatis-Plus 中 Mapper 重载踩坑指南</a><time datetime="2021-08-21T23:00:00.000Z" title="发表于 2021-08-22 07:00:00">2021-08-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/MODJ8j-9ObHeB.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="并发场景加锁优化小技巧"/></a><div class="content"><a class="title" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧">并发场景加锁优化小技巧</a><time datetime="2021-07-24T23:00:00.000Z" title="发表于 2021-07-25 07:00:00">2021-07-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"/></a><div class="content"><a class="title" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁">ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁</a><time datetime="2021-07-16T13:30:30.000Z" title="发表于 2021-07-16 21:30:30">2021-07-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"/></a><div class="content"><a class="title" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁">ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁</a><time datetime="2021-07-15T13:30:30.000Z" title="发表于 2021-07-15 21:30:30">2021-07-15</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2017 - 2021 By liuzhihang</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><img class="icp-icon" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="/resources/image/icp.png"><span>备案号：京ICP备20000888号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>function addGitalkSource () {
  const ele = document.createElement('link')
  ele.rel = 'stylesheet'
  ele.href= 'https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.css'
  document.getElementsByTagName('head')[0].appendChild(ele)
}

function loadGitalk () {
  function initGitalk () {
    var gitalk = new Gitalk(Object.assign({
      clientID: 'e48f300349e2ac2d03bd',
      clientSecret: '001c669e6269dfd9d7d9fef029cc71fd00ea69e3',
      repo: 'comments',
      owner: 'liuzhihang',
      admin: ['liuzhihang'],
      id: '59da5d4b9589faa05323b771c9d81e31',
      language: 'en',
      perPage: 10,
      distractionFreeMode: false,
      pagerDirection: 'last',
      createIssueManually: false,
      updateCountCallback: commentCount
    },null))

    gitalk.render('gitalk-container')
  }

  if (typeof Gitalk === 'function') initGitalk()
  else {
    addGitalkSource()
    getScript('https://cdn.jsdelivr.net/npm/gitalk@latest/dist/gitalk.min.js').then(initGitalk)
  }
}

function commentCount(n){
  let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
  if (isCommentCount) {
    isCommentCount.innerHTML= n
  }
}

if ('Gitalk' === 'Gitalk' || !false) {
  if (false) btf.loadComment(document.getElementById('gitalk-container'), loadGitalk)
  else loadGitalk()
} else {
  function loadOtherComment () {
    loadGitalk()
  }
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>